﻿using System.IO;
using System.Text;
using Ude;

namespace NetSurveillance.WebApp.Utilities
{
    public class EncodeUtility
    {
        public static string Convert(string filePath, Encoding transEncoding = null)
        {
            if (transEncoding == null)
                transEncoding = Encoding.UTF8;
            if (string.IsNullOrWhiteSpace(filePath) ||
                !File.Exists(filePath))
                return null;
            using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                CharsetDetector charDect = new CharsetDetector();
                charDect.Feed(fs);
                charDect.DataEnd();
                if (!string.IsNullOrWhiteSpace(charDect.Charset))
                {
                    var fileEncoding = Encoding.GetEncoding(charDect.Charset);
                    byte[] fileBytes = new byte[fs.Length];
                    if (fs.Read(fileBytes, 0, fileBytes.Length) > 0)
                    {
                        return transEncoding.GetString(Encoding.Convert(fileEncoding, transEncoding, fileBytes));
                    }
                }
            }
            return null;
        }
    }
}